package cn.iocoder.yudao.module.infrastructure.region.service;

import cn.hutool.core.lang.tree.Tree;
import cn.iocoder.yudao.framework.ip.IpSearchUtils;
import cn.iocoder.yudao.framework.location.LocationClient;
import cn.iocoder.yudao.framework.location.LocationClientFactory;
import cn.iocoder.yudao.framework.location.LocationInfo;
import cn.iocoder.yudao.framework.location.LocationProvider;
import cn.iocoder.yudao.framework.region.CityUtils;
import cn.iocoder.yudao.framework.region.PinyinUtils;
import cn.iocoder.yudao.framework.region.RegionUtils;
import cn.iocoder.yudao.framework.region.enums.CityDataSet;
import cn.iocoder.yudao.framework.region.enums.RegionDataSet;
import cn.iocoder.yudao.framework.region.vo.CityVO;
import cn.iocoder.yudao.module.infrastructure.region.vo.PinyinCityVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/17
 */
@Service
public class RegionServiceImpl implements RegionService {

    @Override
    public List<Tree<Integer>> getRegionTree() {
        return RegionUtils.getRegionTree(RegionDataSet.ONLY_LATEST);
    }

    @Override
    public List<PinyinCityVO> getCityList(String dataset) {
        List<CityVO> list = CityUtils.getList(CityDataSet.getByCode(dataset));
        return list.stream().map(region -> {
            PinyinCityVO respVO = new PinyinCityVO();
            respVO.setCode(region.getCityCode());
            respVO.setName(region.getCityName());
            respVO.setAlphabet(PinyinUtils.toAlphabet(region.getCityName()));
            return respVO;
        }).toList();
    }

    @Override
    public String getCityByIp(String ip) {
        return IpSearchUtils.getCity(ip);
    }

    @Override
    public LocationInfo getLocation(Double longitude, Double latitude, String provider) {
        LocationProvider locationProvider = LocationProvider.getByCode(provider);
        LocationClient client;
        if (locationProvider == null) {
            client = LocationClientFactory.createRandom();
        } else {
            client = LocationClientFactory.create(locationProvider);
        }
        return client.getLocation(longitude, latitude);
    }

    @Override
    public String getLocationAddress(Double longitude, Double latitude, String provider) {
        return getLocation(longitude, latitude, provider).getFormattedAddress();
    }

}
